<?php

include_once './Image.php';
include_once './BMP.php';
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Wil
 *
 * @author 梅小春 476984957@qq.com
 */
class Wil {

    public $file;

    /** 标题 */
    public $title;

    /** 图片数量 */
    public $imageCount;

    /** 色深度 */
    public $colorCount;

    /** 调色板字节数 */
    public $paletteSize;
    /* 调色板 */
    public $palette;
    /*     * 图片数组 */
    public $images;
    public $wix;

    public static function getObject($file, Wix $wix) {
        $obj = new Wil();
        $obj->file = $file;
        $obj->wix = $wix;
        $f = fopen($file, 'rb');
        $obj->title = Reader::getTitle($f);
        $obj->imageCount = Reader::Integer($f); //读取4字节转成int ,图片长度
        $obj->colorCount = Reader::Integer($f); //读取4字节 色深度
        $obj->paletteSize = Reader::Integer($f);
        $length = intval($obj->paletteSize / 4); //调色板大小
        $obj->palette= self::readPalatte($f, $length);// 读取调色板数据
        fclose($f);
        return $obj;
    }
    
    /**
     * 设置调色板数据，这里主要是处理黑色
     * @param type $f
     * @param type $length
     * @return string
     */
    private static function readPalatte(&$f,$length){
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $byteArgb = Reader::getBytes($f, 4);
            if ($byteArgb[2] == 0 && $byteArgb[1] == 0 && $byteArgb[0] == 0) {
                $byteArgb[3] = 0;
            } else {
                $byteArgb[3] = 255;
            }
            foreach ($byteArgb as &$one) {
                $one = chr($one);
            }
            $str = $str . implode("", $byteArgb);
        }
        return $str;
    }


    /**
     * 获取调色板长度
     * @return type
     */
    public function getPlatteLength(){
        return intval($this->paletteSize / 4);
    }
    /**
     * 读取 wil 库中的bmp数据
     */
    public function readImages() {
        $this->images = [];
        $f = fopen($this->file, 'rb');
        for ($i = 0; $i < $this->imageCount; $i++) {
            $image = Image::getImage($f, $this->wix->imageIndexs[$i], $this->getBit());
            array_push($this->images, $image);
//            BMP::save($this->palette, $image->bmpData,$this->getPlatteLength(), $image->width, $image->height, $this->getBit(), "./test.bmp");
        }
        fclose($f);
    }

    public function getBit() {
        if ($this->colorCount == 256) {
            return 8;
        } else if ($this->colorCount == 65536) {
            return 16;
        } else if ($this->colorCount == 16777216) {
            return 24;
        } else {
            return 32;
        }
    }

}
